//index.js
//获取应用实例
let app = getApp()
let NORMAL = 0, PULLDOWN = 2
Page({
  data: {
    autoplay: true,
    interval: 3000,
    duration: 1000,
    swiperCurrent: 0,
    scrollTop: 0,
    hasNoCoupons: false,
    coupons: [],
    banners: [],
    // labelIDList: [],
    suggestList: [],
    suggestID: 0,
    chosenList: [],
    chosenID: 0,
    hotSaleList: [],
    hotSaleID: 0,
    newList: [],
    newID: 0,
    secondKillList: [],
    secondKillActList: []
  },

  onLoad: function () {
  
  },

  initData: function (flag) {
    this.getBannerList(flag)
    this.getSecondKillList(flag)
    this.getLabelList('店主推荐', flag)
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
      this.initData(NORMAL)
  },

  //事件处理函数
  swiperchange: function (e) {
    //console.log(e.detail.current)
    this.setData({
      swiperCurrent: e.detail.current
    })
  },
  /**
   * 查看商品详情
   */
  toDetailsTap: function (e) {
    wx.navigateTo({
      url: "/pages/goods-details/index?id=" + e.currentTarget.dataset.id + "&type=0"
    })
  },
  /**
   * 查看秒杀商品详情
   */
  toSecDetailsTap: function (e) {
  
    wx.navigateTo({
      url: "/pages/goods-details/index?id=" + e.currentTarget.dataset.id + "&type=1" + "&endtime=" + JSON.stringify(this.data.endTime)
    })
    
  },
  /**
   * 点击轮播图
   */
  tapBanner: function (e) {
    // if (e.currentTarget.dataset.id != 0) {
    //   wx.navigateTo({
    //     url: "/pages/goods-details/index?id=" + '4466'//for test
    //   })
    // }
  },
  /**
   * 跳转至优惠券列表
   */
  toGetCoupons: function (e) {
    wx.navigateTo({
      url: "/pages/get-coupons/index"
    })
  },

  /**
   * 跳转至lottery页面
   */
  toLottery: function (e) {
    wx.navigateTo({
      url: "/pages/lottery/index"
    })
  },

  onPullDownRefresh: function () {
    wx.showNavigationBarLoading()
    this.initData(PULLDOWN)
  },
  onPageScroll: function (e) {
    //console.log(e)
    //var that = this
    //var that = this, scrollTop = that.data.scrollTop;
    //scrollTop = e.scrollTop
    // if (e.scrollTop >= 100 && !this.data.becomeWhite) {
    //   this.data.becomeWhite = true
    //   this.setData({
    //     searchBackground: 'rgba(255, 255, 255, 1)'
    //   })
    // }else if (e.scrollTop < 100 && this.data.becomeWhite){
    //   this.data.becomeWhite = false
    //   this.setData({
    //     searchBackground: 'rgba(255, 255, 255, 0.3)'
    //   })
    // }
    // this.setData({
    //   scrollTop: e.scrollTop
    // })
    //console.log(this.data.scrollTop)
    //console.log('e.detail.scrollTop:'+e.detail.scrollTop)
    //console.log('scrollTop:'+scrollTop)
  },
  listenerSearchInput: function (e) {
    this.setData({
      searchInput: e.detail.value
    })

  },
  // toSearch: function () {
  //   this.getGoodsList(this.data.activeCategoryId);
  // },

  /**
   * 获取轮播图信息
   */
  getBannerList: function (flag) {
    let token = wx.getStorageSync('token')
    let bannersTemp = []
    let that = this
    console.log('banners')
    wx.request({
      url: app.apiUrl('/index/viewpage'),
      method: 'GET',
      header: {
        "Authorization": 'Bearer ' + token
      },
      data: {
        
      },
      success: function (res) {
        //console.log(res.data)
        if (res.data.code > app.globalData.successCode) {
          wx.showToast({
            title: res.data.error_message ? res.data.error_message : app.globalData.unknownError,
            icon: 'none',
            duration: 2000
          })
        } else if (res.data.code == app.globalData.successCode) {
          app.login(that, 1)
        } else {
          if (res.data.data) {
            for (var i = 0; i < res.data.data.length; i++) {
              res.data.data[i].pic_url = app.globalData.imgUrl + res.data.data[i].pic_url
            }
            that.setData({
              banners: res.data.data
            })
          } else {
            wx.showModal({
              title: '提示',
              content: '服务器异常',
              showCancel: false
            })
          }
          
        }
        
      },
      fail: function (res) {
        console.log(res)
      },
      complete: function (res) {
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
      }
    })
  },

  /**
   * 获取标签信息
   */
  getLabelList: function (name, flag) {
    let token = wx.getStorageSync('token')
    let that = this
    //console.log('labels')
    wx.request({
      url: app.apiUrl('/product/label'),
      method: 'GET',
      header: {
        "Authorization": 'Bearer ' + token
      },
      data: {
        label_name: name    
      },
      success: function (res) {
        console.log('getLabelList')
        console.log(res.data)
        if (res.data.code > app.globalData.successCode) {
          wx.showToast({
            title: res.data.error_message ? res.data.error_message : app.globalData.unknownError,
            icon: 'none',
            duration: 2000
          })
        } else if (res.data.code == app.globalData.successCode) {
          app.login(that, 1)
        } else {
          if (res.data.data)
            that.getProductList(res.data.data.id, name, flag)
        }

      },
      fail: function (res) {
        console.log(res)
      },
      complete: function (res) {
        // wx.hideToast()
        //console.log(res)
      }
    })
  },

  /**
   * 获取商品列表
   */
  getProductList: function (id, labelName, flag) {
    let token = wx.getStorageSync('token')
    let that = this
    console.log('products')
    console.log('id:' + id)
    wx.request({
      url: app.apiUrl('/product/list'),
      method: 'GET',
      header: {
        "Authorization": 'Bearer ' + token
      },
      data: {
        label_id: id
      },
      success: function (res) {
        console.log(res.data)
        let productListTemp = []
        if (res.data.code > app.globalData.successCode) {
          wx.showToast({
            title: res.data.error_message ? res.data.error_message : app.globalData.unknownError,
            icon: 'none',
            duration: 2000
          })
        } else if (res.data.code == app.globalData.successCode) {
          app.login(that, 1)
        } else {
          for (var i = 0; i < res.data.data.length; i++) {
            res.data.data[i].pic_url = app.globalData.imgUrl + res.data.data[i].file.savepath + res.data.data[i].file.savename
            res.data.data[i].price = res.data.data[i].price.toFixed(2)
            res.data.data[i].old_price = res.data.data[i].old_price.toFixed(2)
            productListTemp.push(res.data.data[i])
          }
          // if (id == 1)
          if (labelName == '店主推荐') {
            that.setData({
              suggestList: productListTemp.slice(0, 6),//for test
              suggestID: id
            })
            that.getLabelList('精选好货', flag)
          } else if (labelName == '精选好货') {
            that.setData({
              chosenList: productListTemp.slice(0, 6),//for test
              chosenID: id
            })
            that.getLabelList('人气热卖', flag)
          } else if (labelName == '人气热卖') {
            that.setData({
              hotSaleList: productListTemp.slice(0, 6),//for test
              hotSaleID: id 
            })
            that.getLabelList('新品上市', flag)
          } else if (labelName == '新品上市') {
            that.setData({
              newList: productListTemp.slice(0, 6),//for test
              newID: id
            })
          }
            
        }
        
      },
      fail: function (res) {
        console.log(res)
      },
      complete: function (res) {
        if (flag == that.data.PULLDOWN) {
          wx.hideNavigationBarLoading() //完成停止加载
          wx.stopPullDownRefresh() //停止下拉刷新
        }
      }
    })
  },

  /**
   * 跳转至秒杀列表
   */
  toSecondKill: function () {
    if (this.data.secondKillActList.length > 0) {
      // wx.navigateTo({
      //   url: "/pages/seconds-kill-products/index"
      // })

      wx.navigateTo({
        url: "/pages/seconds-kill-list/index"
      })
    }
      
  },

  toSearch: function () {
    wx.navigateTo({
      url: "/pages/search/index?fromID=0"
    });

    // wx.navigateTo({
    //   url: "/pages/seconds-kill-list/index"
    // });
  },

  /**
   * 获取秒杀商品列表
   */
  getSecondKillList: function () {
    let token = wx.getStorageSync('token')
    let that = this
    wx.request({
      url: app.apiUrl('/product/seckilllist'),
      method: 'GET',
      header: {
        "Authorization": 'Bearer ' + token
      },
      data: {

      },
      success: function (res) {
        console.log('getSecondKill')
        console.log(res.data)
        if (res.data.code > app.globalData.successCode) {
          wx.showToast({
            title: res.data.error_message ? res.data.error_message : app.globalData.unknownError,
            icon: 'none',
            duration: 2000
          })
        } else if (res.data.code == app.globalData.successCode) {
          app.login(that, 1)
        } else {
          if (res.data.data.length > 0) {
            let listTemp = res.data.data.filter(function (curSecond) {
              return curSecond.now == 1
            })
            let productList = []
            if (listTemp.length > 0) {

              productList = listTemp[0].seckill_product
              for (var i = 0; i < productList.length; i++) {
                productList[i].pic_url = app.globalData.imgUrl + productList[i].product.file.savepath + productList[i].product.file.savename
                productList[i].product.price = res.data.data[0].seckill_product[i].product.price.toFixed(2)
                productList[i].product.old_price = res.data.data[0].seckill_product[i].product.old_price.toFixed(2)
              }
            }

            that.setData({
              secondKillList: productList,
              secondKillActList: res.data.data,
              endTime: listTemp.length > 0 ? listTemp[0].end_at : ""
            })

          }
          

        }
      },
      fail: function (res) {
        console.log(res)
      },
      complete: function (res) {
        // // wx.hideToast()
        // //console.log(res)
        // wx.hideNavigationBarLoading() //完成停止加载
        // wx.stopPullDownRefresh() //停止下拉刷新
      }
    })
  },

  toSuggest: function () {
    let that = this
    wx.navigateTo({
      url: "/pages/category/list?label_id=" + that.data.suggestID  
    })
  },
  toChosen: function () {
    let that = this
    wx.navigateTo({
      url: "/pages/category/list?label_id=" + that.data.chosenID
    })
  },
  
  toHotSale: function () {
    let that = this
    wx.navigateTo({
      url: "/pages/category/list?label_id=" + that.data.hotSaleID
    })
  },

  toNew: function () {
    let that = this
    wx.navigateTo({
      url: "/pages/category/list?label_id=" + that.data.newID
    })
  },

})
